package com.moive.news.tqnewsapplication.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.DyReleaseEntity;
import com.moive.news.tqnewsapplication.event.SenEvent;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.photo.PhotoPickerActivity;
import com.moive.news.tqnewsapplication.photo.utils.ImageLoader;
import com.moive.news.tqnewsapplication.photo.utils.OtherUtils;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsManager;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsResultAction;
import com.moive.news.tqnewsapplication.utils.FalseClickListener;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.MakeLoading;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.TimeUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.ClearEditText;
import com.upyun.library.common.Params;
import com.upyun.library.common.ResumeUploader;
import com.upyun.library.common.UploadEngine;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;
import com.upyun.library.utils.UpYunUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

import static com.moive.news.tqnewsapplication.networks.BaseApi.BASEUR_IMG;
import static com.moive.news.tqnewsapplication.networks.BaseApi.PASSWORD;


/**
 * Created by Administrator on 2017/12/13.
 */

public class PutDynamicActivity extends BaseActivity implements View.OnClickListener {
    private ClearEditText activityReleaseText;
    private TextView dyReleaseAddr;
    private TextView releaseNum;
    private GridView releaseGridView;
    private TextView releasePicNum;
    private int MAX_LENGTH = 200;
    private int MAX_PIC_LENGTH = 9;
    private ImageView addImg;
    private static final int PICK_PHOTO = 1;
    private List<String> mResults = new ArrayList<>();
    private GridAdapter mAdapter;
    private GridAdapter gridAdapter;
    private int mColumnWidth;
    private Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    private LinearLayout selectAddr;
    private RelativeLayout relativeLayout;
    private List<DyReleaseEntity> dyReleaseEntityList = new ArrayList<>();
    private MakeLoading dialog;
    private ImageView setting_back;
    private TextView textRight;
    private ResumeUploader uploader;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_putdyamic);
        init();
    }

    private void init() {
        dialog=new MakeLoading(PutDynamicActivity.this);
        int screenWidth = OtherUtils.getWidthInPx(getApplicationContext());
        mColumnWidth = (screenWidth - OtherUtils.dip2px(getApplicationContext(), 4)) / 3;
        releasePicNum = (TextView) findViewById(R.id.releasePicNum);
        releaseGridView = (GridView) findViewById(R.id.releaseGridView);
        releaseNum = (TextView) findViewById(R.id.releaseNum);
        dyReleaseAddr = (TextView) findViewById(R.id.dyReleaseAddr);
        relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        selectAddr = (LinearLayout) findViewById(R.id.selectAddr);
        selectAddr.setOnClickListener(this);
        activityReleaseText = (ClearEditText) findViewById(R.id.activityReleaseText);
        dyReleaseAddr.setText("请选择地址！");
        addImg = (ImageView) findViewById(R.id.addImg);
        addImg.setOnClickListener(this);
        releaseNum.setText("0" + "/" + MAX_LENGTH);
        initlickListener();
        dyReleaseEntityList.clear();
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("1");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        gridAdapter = new GridAdapter(dyReleaseEntityList);
        releaseGridView.setAdapter(gridAdapter);
        gridAdapter.notifyDataSetChanged();
        dialog = new MakeLoading(PutDynamicActivity.this);
        setting_back = (ImageView) findViewById(R.id.setting_back_02);
        setting_back.setOnClickListener(this);
        textRight = (TextView) findViewById(R.id.textRight);
        textRight.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_back_02:
                finish();
                break;
            case R.id.textRight:
                if (FalseClickListener.isFastDoubleClick()) {
                    ToastUtils.ShortToast("动态发表中，请勿重复点击!");
                    return;
                }
                updynamic();
                break;
        }
    }

    private void initlickListener() {
        activityReleaseText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = activityReleaseText.getText().toString();
                releaseNum.setText(content.length() + "/" + MAX_LENGTH);
                if (content.length() > MAX_LENGTH) {
                    ToastUtils.ShortToast("您输入的内容已达上限，请精简内容！");
                    activityReleaseText.setEnabled(false);
                } else {
                    activityReleaseText.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                showResult(result);
            }
        }
    }

    private void showResult(ArrayList<String> paths) {
        mResults.clear();
        dyReleaseEntityList.clear();
        gridAdapter.notifyDataSetChanged();
        for (int i = 0; i < paths.size(); i++) {
            DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
            dyReleaseEntity.setImgPath(paths.get(i));
            dyReleaseEntity.setImgType("1");
            dyReleaseEntityList.add(dyReleaseEntity);
//            mResults.add(paths.get(i));
        }
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("2");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        if (mAdapter == null) {
            mAdapter = new GridAdapter(dyReleaseEntityList);
        }
        releaseGridView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        releasePicNum.setText(dyReleaseEntityList.size() - 1 + "/" + MAX_PIC_LENGTH);
        if (dyReleaseEntityList.size() > 8) {
            dyReleaseEntityList.remove(9);
        }
        //上传图片
        upimg();
    }

    private class GridAdapter extends BaseAdapter {
        private List<DyReleaseEntity> pathList;

        public GridAdapter(List<DyReleaseEntity> pathList) {
            this.pathList = pathList;
        }

        @Override
        public int getCount() {
            return pathList.size();
        }

        @Override
        public Object getItem(int position) {
            return pathList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mColumnWidth, mColumnWidth);
                holder.imageView.setLayoutParams(params);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (pathList.get(position).getImgType().equals("2")) {
                holder.imageView.setBackgroundResource(R.drawable.add02);
                holder.imageView.setEnabled(true);
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       check();
                    }
                });
            } else {
                ImageLoader.getInstance().display(pathList.get(position).getImgPath(), holder.imageView, mColumnWidth, mColumnWidth);
                holder.imageView.setEnabled(false);
            }
            return convertView;
        }
        private class ViewHolder {
            public ImageView imageView;
        }
    }
    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(PutDynamicActivity.this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                go();
            }

            @Override
            public void onDenied(String permission) {
                ToastUtils.ShortToast("用户拒绝授权");
            }
        });
    }
    private void go(){
        Intent intent = new Intent(PutDynamicActivity.this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, MAX_PIC_LENGTH);
        startActivityForResult(intent, PICK_PHOTO);
    }
    private void updynamic() {
        LogUtil.i("lidaming","mResults="+mResults.size()+mResults.toString());
        String content = activityReleaseText.getText().toString();
        if (TextUtils.isEmpty(content)) {
            ToastUtils.ShortToast("发表内容不能为空！");
            return;
        }
        String token = PreferenceUtil.getString("token", "");
        if (TextUtils.isEmpty(token)) {
            ToastUtils.ShortToast("您还未登录，请在首页我的界面前往登录!");
        }
        String jsonArray=gson.toJson(mResults.toArray());
        LogUtil.i("lidaming","jsonArray="+jsonArray);
  Map<String,String> hash=new HashMap<>();
        hash.put("content", content);
        hash.put("token", token);
        hash.put("images",jsonArray);
       OkHttpUtils.post()
                .url(BaseApi.PUTDYNA)
               .params(hash)
               .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }
            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        ToastUtils.ShortToast("发表成功！");
                        EventBus.getDefault().post(new SenEvent("1"));
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upimg() {
        final Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET,BaseApi.SPACE);
        //保存路径，任选其中一个
        //        dyReleaseEntityList
        String date= TimeUtil.parseDate(new Date().getTime());
        for (int i=0;i<dyReleaseEntityList.size()-1;i++){
            File file=null;
            String filepath=dyReleaseEntityList.get(i).getImgPath();
            LogUtil.i("lidaming",filepath);
             String geshi=filepath.substring(filepath.lastIndexOf("."));
             String  savePath="/uploads/"+date+"/"+UUID.randomUUID().toString().replaceAll("-","")+geshi;
            file=new File(filepath);
            //表单上传（本地签名方式）
            paramsMap.put(Params.SAVE_KEY, savePath);
            UploadEngine.getInstance().formUpload(file, paramsMap, BaseApi.OPERATER, UpYunUtils.md5(PASSWORD), completeListener, progressListener);
        }
    }
    //结束回调，不可为空
    UpCompleteListener completeListener = new UpCompleteListener() {
        @Override
        public void onComplete(boolean isSuccess, String result) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            Log.e(TAG, isSuccess + ":" + result);
            if (isSuccess==true){
//                mResults.add(paths.get(i));
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String url=jsonObject.getString("url");
                    mResults.add(BASEUR_IMG+url);
                    ToastUtils.ShortToast("上传图片成功！");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else {
                ToastUtils.ShortToast("上传图片失败！");
            }
        }
    };
    //进度回调，可为空
    UpProgressListener progressListener = new UpProgressListener() {
        @Override
        public void onRequestProgress(final long bytesWrite, final long contentLength) {
//            uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
//            textView.setText((100 * bytesWrite) / contentLength + "%");
            Log.e(TAG, (100 * bytesWrite) / contentLength + "%");
            if ((100 * bytesWrite) / contentLength==100){
                    dialog.dismiss();
            }else {
                    dialog.show();
            }
            Log.e(TAG, bytesWrite + "::" + contentLength);
        }
    };
}